use crate::traits::{ConnectorFactory, ConnectorMetadata, ConnectorType, SyncMode};
use crate::sources::{HttpSourceConnector, DatabaseSourceConnector, FileSourceConnector};
use crate::destinations::{DatabaseDestinationConnector, FileDestinationConnector, HttpDestinationConnector};
use fluviox_shared::Result;
use serde_json::json;
use std::collections::HashMap;

/// 连接器注册表
pub struct ConnectorRegistry {
    supported_sources: Vec<String>,
    supported_destinations: Vec<String>,
}

impl ConnectorRegistry {
    pub fn new() -> Self {
        Self {
            supported_sources: vec![
                "http".to_string(),
                "database".to_string(),
                "file".to_string(),
            ],
            supported_destinations: vec![
                "database".to_string(),
                "file".to_string(),
                "http".to_string(),
            ],
        }
    }

    /// 创建HTTP数据源连接器
    pub fn create_http_source(&self) -> HttpSourceConnector {
        HttpSourceConnector::new()
    }

    /// 创建数据库数据源连接器
    pub fn create_database_source(&self) -> DatabaseSourceConnector {
        DatabaseSourceConnector::new()
    }

    /// 创建文件数据源连接器
    pub fn create_file_source(&self) -> FileSourceConnector {
        FileSourceConnector::new()
    }

    /// 创建数据库目标连接器
    pub fn create_database_destination(&self) -> DatabaseDestinationConnector {
        DatabaseDestinationConnector::new()
    }

    /// 创建文件目标连接器
    pub fn create_file_destination(&self) -> FileDestinationConnector {
        FileDestinationConnector::new()
    }

    /// 创建HTTP目标连接器
    pub fn create_http_destination(&self) -> HttpDestinationConnector {
        HttpDestinationConnector::new()
    }

    /// 获取支持的数据源连接器列表
    pub fn list_sources(&self) -> Vec<String> {
        self.supported_sources.clone()
    }

    /// 获取支持的目标连接器列表
    pub fn list_destinations(&self) -> Vec<String> {
        self.supported_destinations.clone()
    }
}

impl ConnectorFactory for ConnectorRegistry {
    fn create_source(&self, connector_type: &str) -> Result<Box<dyn std::any::Any + Send + Sync>> {
        match connector_type {
            "http" => Ok(Box::new(self.create_http_source())),
            "database" => Ok(Box::new(self.create_database_source())),
            "file" => Ok(Box::new(self.create_file_source())),
            _ => Err(fluviox_shared::FluvioXError::Internal(
                format!("未知的数据源连接器类型: {}", connector_type)
            ))
        }
    }

    fn create_destination(&self, connector_type: &str) -> Result<Box<dyn std::any::Any + Send + Sync>> {
        match connector_type {
            "database" => Ok(Box::new(self.create_database_destination())),
            "file" => Ok(Box::new(self.create_file_destination())),
            "http" => Ok(Box::new(self.create_http_destination())),
            _ => Err(fluviox_shared::FluvioXError::Internal(
                format!("未知的目标连接器类型: {}", connector_type)
            ))
        }
    }
    
    fn supported_sources(&self) -> Vec<ConnectorMetadata> {
        vec![
            ConnectorMetadata {
                name: "http".to_string(),
                version: "1.0.0".to_string(),
                description: "HTTP/REST API数据源连接器".to_string(),
                connector_type: ConnectorType::Source,
                supported_sync_modes: vec![SyncMode::RealTime, SyncMode::Incremental],
                configuration_schema: json!({
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": "API端点URL"
                        },
                        "method": {
                            "type": "string",
                            "enum": ["GET", "POST", "PUT", "DELETE"],
                            "default": "GET",
                            "description": "HTTP方法"
                        },
                        "headers": {
                            "type": "object",
                            "description": "请求头"
                        },
                        "poll_interval": {
                            "type": "integer",
                            "minimum": 1,
                            "default": 60,
                            "description": "轮询间隔（秒）"
                        }
                    },
                    "required": ["url"]
                }),
            },
            ConnectorMetadata {
                name: "database".to_string(),
                version: "1.0.0".to_string(),
                description: "数据库数据源连接器".to_string(),
                connector_type: ConnectorType::Source,
                supported_sync_modes: vec![SyncMode::FullRefresh, SyncMode::Incremental],
                configuration_schema: json!({
                    "type": "object",
                    "properties": {
                        "connection_url": {
                            "type": "string",
                            "description": "数据库连接URL"
                        },
                        "query": {
                            "type": "string",
                            "description": "查询SQL"
                        },
                        "poll_interval": {
                            "type": "integer",
                            "minimum": 1,
                            "default": 300,
                            "description": "轮询间隔（秒）"
                        }
                    },
                    "required": ["connection_url", "query"]
                }),
            },
            ConnectorMetadata {
                name: "file".to_string(),
                version: "1.0.0".to_string(),
                description: "文件数据源连接器".to_string(),
                connector_type: ConnectorType::Source,
                supported_sync_modes: vec![SyncMode::FullRefresh, SyncMode::RealTime],
                configuration_schema: json!({
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "文件或目录路径"
                        },
                        "format": {
                            "type": "string",
                            "enum": ["json", "jsonlines", "csv", "text"],
                            "default": "jsonlines",
                            "description": "文件格式"
                        },
                        "watch_mode": {
                            "type": "boolean",
                            "default": false,
                            "description": "是否监控文件变化"
                        }
                    },
                    "required": ["path"]
                }),
            },
        ]
    }
    
    fn supported_destinations(&self) -> Vec<ConnectorMetadata> {
        vec![
            ConnectorMetadata {
                name: "database".to_string(),
                version: "1.0.0".to_string(),
                description: "数据库目标连接器".to_string(),
                connector_type: ConnectorType::Destination,
                supported_sync_modes: vec![SyncMode::FullRefresh, SyncMode::Incremental],
                configuration_schema: json!({
                    "type": "object",
                    "properties": {
                        "connection_url": {
                            "type": "string",
                            "description": "数据库连接URL"
                        },
                        "table_name": {
                            "type": "string",
                            "description": "目标表名"
                        },
                        "write_mode": {
                            "type": "string",
                            "enum": ["insert", "upsert", "replace"],
                            "default": "insert",
                            "description": "写入模式"
                        },
                        "batch_size": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 10000,
                            "default": 1000,
                            "description": "批次大小"
                        }
                    },
                    "required": ["connection_url", "table_name"]
                }),
            },
            ConnectorMetadata {
                name: "file".to_string(),
                version: "1.0.0".to_string(),
                description: "文件目标连接器".to_string(),
                connector_type: ConnectorType::Destination,
                supported_sync_modes: vec![SyncMode::FullRefresh, SyncMode::Incremental],
                configuration_schema: json!({
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "输出文件路径"
                        },
                        "format": {
                            "type": "string",
                            "enum": ["json", "jsonlines", "csv", "text"],
                            "default": "jsonlines",
                            "description": "文件格式"
                        },
                        "write_mode": {
                            "type": "string",
                            "enum": ["overwrite", "append", "create_new"],
                            "default": "append",
                            "description": "写入模式"
                        },
                        "batch_size": {
                            "type": "integer",
                            "minimum": 1,
                            "default": 1000,
                            "description": "批次大小"
                        }
                    },
                    "required": ["path"]
                }),
            },
            ConnectorMetadata {
                name: "http".to_string(),
                version: "1.0.0".to_string(),
                description: "HTTP目标连接器".to_string(),
                connector_type: ConnectorType::Destination,
                supported_sync_modes: vec![SyncMode::RealTime, SyncMode::Incremental],
                configuration_schema: json!({
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": "目标URL"
                        },
                        "method": {
                            "type": "string",
                            "enum": ["GET", "POST", "PUT", "DELETE", "PATCH"],
                            "default": "POST",
                            "description": "HTTP方法"
                        },
                        "headers": {
                            "type": "object",
                            "description": "请求头"
                        },
                        "format": {
                            "type": "string",
                            "enum": ["json", "jsonlines", "text", "form_data"],
                            "default": "json",
                            "description": "数据格式"
                        },
                        "batch_size": {
                            "type": "integer",
                            "minimum": 1,
                            "default": 100,
                            "description": "批次大小"
                        }
                    },
                    "required": ["url"]
                }),
            },
        ]
    }
}

impl Default for ConnectorRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// 全局连接器注册表实例
static mut GLOBAL_REGISTRY: Option<ConnectorRegistry> = None;
static INIT: std::sync::Once = std::sync::Once::new();

/// 获取全局连接器注册表
pub fn get_global_registry() -> &'static ConnectorRegistry {
    unsafe {
        INIT.call_once(|| {
            GLOBAL_REGISTRY = Some(ConnectorRegistry::new());
        });
        GLOBAL_REGISTRY.as_ref().unwrap()
    }
}

/// 获取可变的全局连接器注册表（用于注册自定义连接器）
pub fn get_global_registry_mut() -> &'static mut ConnectorRegistry {
    unsafe {
        INIT.call_once(|| {
            GLOBAL_REGISTRY = Some(ConnectorRegistry::new());
        });
        GLOBAL_REGISTRY.as_mut().unwrap()
    }
}
